package cn.wolfcode.p2p.base.controller;

import cn.wolfcode.p2p.base.anno.NeedLogin;
import cn.wolfcode.p2p.business.domain.RechargeOffline;
import cn.wolfcode.p2p.business.domain.RechargeOnline;
import cn.wolfcode.p2p.business.service.IPlatformBankInfoService;
import cn.wolfcode.p2p.business.service.IRechargeOfflineService;
import cn.wolfcode.p2p.business.service.IRechargeOnlineService;
import cn.wolfcode.p2p.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Enumeration;

/**
 * 前台充值页面
 */
@Controller
public class RechargeController {

    @Autowired
    private IRechargeOfflineService offlineService;
    @Autowired
    private IPlatformBankInfoService bankInfoService;
    @Autowired
    private IRechargeOnlineService onlineService;

    /**
     * 显示充值页面
     *
     * @param model
     * @return
     */
    @RequestMapping("recharge")
    @NeedLogin
    public String recharge(Model model) {

        model.addAttribute("banks", bankInfoService.listAll());
        return "recharge";
    }

    /**
     * 线下申请充值
     *
     * @param rechargeOffline
     * @return
     */
    @RequestMapping("recharge_save")
    @ResponseBody
    public JsonResult rechargeSave(RechargeOffline rechargeOffline) {

        offlineService.apply(rechargeOffline);
        return JsonResult.instance();
    }

    /**
     * 线上托管充值
     * 无返回值,但需要返回结果给浏览器, 因此贴ResponseBody
     *
     * @return
     */
    @RequestMapping("rechargeOnline")
    @ResponseBody
    public void rechargeOnline(BigDecimal amount, HttpServletResponse response) throws IOException {

        String html = onlineService.apply(amount);
        PrintWriter writer = response.getWriter();
        //响应"托管充值页面"地址 给到浏览器
        writer.write(html);

    }

    /**
     * 充值页面同步跳转
     *
     * @return
     */
    @RequestMapping("rechargeResult")
    public String rechargeResult(String tradeCode, Model model) {

        //获取online对象
        RechargeOnline re = onlineService.getTradeCode(tradeCode);
        model.addAttribute("re", re);
        return "recharge_result";
    }

    /**
     * 充值结果异步回调接口
     *
     * @param request
     * @return
     */
    @RequestMapping("rechargeNotify")
    @ResponseBody
    public String rechargeNotify(HttpServletRequest request) {

        return onlineService.resultHandler(request);
    }


}



